<template>
  <div>
    <editor id="tinymce" 
      v-model="myValue"
      :init="init" 
      :disabled="disabled"
      @onClick="onClick">
    </editor>
  </div>
</template>

<script>
  //引入基础文件：
  import tinymce from 'tinymce/tinymce';
  import Editor from '@tinymce/tinymce-vue';
  import 'tinymce/themes/silver';

  // 编辑器插件plugins
  // import 'tinymce/plugins/image'; // 插入上传图片插件
  // import 'tinymce/plugins/link'; // 插入链接
  // import 'tinymce/plugins/code'; // 插入代码
  // import 'tinymce/plugins/preview'; // 插入预览
  // import 'tinymce/icons/default/icons';
  // import 'tinymce/plugins/media'; // 插入视频插件
  // import 'tinymce/plugins/table'; // 插入表格插件
  // import 'tinymce/plugins/lists'; // 列表插件
  // import 'tinymce/plugins/contextmenu';
  // import 'tinymce/plugins/wordcount'; // 字数统计插件
  // import 'tinymce/plugins/paste'; // 粘贴
  // import 'tinymce/plugins/autolink'; // 链接
  // import 'tinymce/plugins/insertdatetime'; // 链接
  // import 'tinymce/plugins/hr'; // 分割线
  // import 'tinymce/plugins/colorpicker';
  // import 'tinymce/plugins/textcolor';
  //由于编辑器上传视频之后无法回显视频,需要修改tinymce下的media插件源码,所以已将node_modules下的tinymce移至src/assets下
  import '../../assets/tinymce/plugins/image';  // 插入上传图片插件
  import '../../assets/tinymce/plugins/link';   // 插入链接
  import '../../assets/tinymce/plugins/code';   // 插入代码
  import '../../assets/tinymce/plugins/preview';  // 插入预览
  import '../../assets/tinymce/icons/default/icons';
  import '../../assets/tinymce/plugins/media';   // 插入视频插件
  import '../../assets/tinymce/plugins/table';   // 插入表格插件
  import '../../assets/tinymce/plugins/lists';   // 列表插件
  import '../../assets/tinymce/plugins/contextmenu';   
  import '../../assets/tinymce/plugins/wordcount';   // 字数统计插件
  import '../../assets/tinymce/plugins/paste';   // 粘贴
  import '../../assets/tinymce/plugins/autolink';  // 链接
  import '../../assets/tinymce/plugins/insertdatetime';   // 链接
  import '../../assets/tinymce/plugins/hr';  // 分割线
  import '../../assets/tinymce/plugins/colorpicker';
  import '../../assets/tinymce/plugins/textcolor';
  import {api} from '../../api/api';
  import {upload} from '../../api/http';
  import {statusCode} from '../../utils/index';

  export default {
    name: "tinymce",
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      disabled: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        video:'',   //上传视频url
        // uploaded:false,   //有没有上传完成
        myValue: this.value,
        init: {
          selector: '#tinymce',
          language_url: '/tinymce/langs/zh_CN.js', // 语言包的路径
          language: 'zh_CN', //语言
          skin_url: '/tinymce/skins/ui/oxide', // skin路径
          height: 500, //编辑器高度
          branding: false, //是否禁用“Powered by TinyMCE”
          menubar: true, //顶部菜单栏显示
          menu: {
            file: { title: 'File', items: 'newdocument restoredraft | preview | print ' },
            edit: { title: 'Edit', items: 'undo redo | cut copy paste | selectall | searchreplace' },
            view: { title: 'View', items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen' },
            insert: { title: 'Insert', items: 'image link media template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime' },
            format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat' },
            tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | code wordcount' },
            table: { title: 'Table', items: 'inserttable | cell row column | tableprops deletetable' },
            help: { title: 'Help', items: 'help' }
          },
          elementpath: false, //禁用编辑器底部的状态栏
          paste_data_images: true, // 允许粘贴图像
          image_advtab: true,
          convert_urls: false,
          plugins: ['image', 'link', 'code', 'preview', 'media', 'table', 'paste', 'wordcount', 'lists', ], //插件
          toolbar: 'bold italic underline strikethrough forecolor backcolor alignleft aligncenter alignright fontsizeselect | alignjustify bullist numlist outdent indent undo redo link unlink image media code removeformat formatselect fontselect',
          content_css:'/tinymce/skins/content/default/content.css?'+ new Date().getTime(),
          resize: false,
          toolbar_mode: 'sliding',
          convert_fonts_to_spans : false,
          fontsize_formats: "12px 14px 16px 20px 22px 26px 28px 36px 48px 56px 72px",
          lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 2',
          content_style: "p {margin: 0px; border:0px ; padding: 0px;}",  //设置行间距
          file_picker_types: 'media',
          font_formats:"宋体='宋体';黑体='黑体';新宋体='新宋体';微软雅黑='微软雅黑';仿宋='仿宋';楷体='楷体';Andale Mono='Andale Mono';Arial='Arial';Arial Black='Arial Black';Book Antiqua='Book Antiqua';Comic Sans MS='Comic Sans MS';Courier New='Courier New';Georgia='Georgia';Helvetica='Helvetica';Impact='Impact';Symbol='Symbol';Tahoma='Tahoma';Terminal='Terminal';Times New Roman='Times New Roman';Trebuchet MS='Trebuchet MS';Verdana='Verdana';Webdings='Webdings';Wingdings='Wingdings'",
          images_upload_handler: (blobInfo, success, failure) => {
            this.handleImageAdded(blobInfo, success, failure)
          },
          file_picker_callback: (callback, value, meta) => {
            this.uploadVideo(callback, value, meta);
          }
        },
      }
    },
    mounted() {
      tinymce.init({})
    },
    activated() {
      tinymce.init({})
    },
    watch: {
      //动态传参
      value(newValue) {
        this.myValue = newValue
      },
      //读取输入框内的数据
      myValue(newValue) {
        this.$emit('input', newValue)
      }
    },
    methods: {
      //需要什么事件可以自己增加
      onClick(e) {
        this.$emit('onClick', e, tinymce)
      },
      //可以添加一些自己的自定义事件，如清空内容
      clear() {
        this.myValue = ''
      },
      //上传图片
      handleImageAdded(blobInfo, success, failure) {
        let file = blobInfo.blob();
        let isLt5 = file.size / 1024 < 512;
        if(!isLt5){
          this.$message.error('图片大小不能超过512K');
          document.getElementsByClassName('tox-dialog__busy-spinner')[0].style.display = 'none';
          return;
        }
        let formdata = new FormData();
        formdata.set('file', file);
        upload(api.upload_url, formdata, (res)=>{
          if(res.data.code === statusCode.success){
            let url = res.data.data.replace('["', '').replace('"]', '');
            success(url);
          }else{
            failure(res.data.data);
            that.$message.error('上传图片失败');
          }
        })
      },
      //上传视频
      uploadVideo(callback, value, meta){
        if(meta.filetype == 'media'){
          let input = document.createElement('input');
          input.setAttribute('type', 'file');
          let that = this;
          input.onchange = function(){
            let file = this.files[0];
            new Promise((resolve)=>{
              let url = URL.createObjectURL(file);
              let audioElement = new Audio(url);
              audioElement.addEventListener("loadedmetadata", () => {
                resolve(audioElement.duration);
              });
            }).then((res)=>{
              let duration = Math.floor(res);
              // 视频时长不超过300s
              if(duration > 300){
                that.$message.error('视频时长不可超过300s');
                return;
              }
              that.upload_video(callback, file, 'media');
            });
            // setTimeout(()=>{
            //   if(that.uploaded){
            //     callback(that.video);
            //   }else{
            //     setTimeout(()=>{
            //       callback(that.video);
            //     }, 1000);
            //   }
            // }, 1000);
          }
          input.click();
        }
      },
      upload_video(callback, file, type){
        let that = this;
        let formdata = new FormData();
        formdata.set('file', file);
        upload(api.upload_url, formdata, (res)=>{
          if(res.data.code === statusCode.success){
            let url = res.data.data.replace('["', '').replace('"]', '');
            if(type == 'media' && url){
              that.video = url;
              // that.uploaded = true;
              callback(that.video);
            }
          }else{
            that.$message.error('上传视频失败');
          }
        })
      }
    },
    beforeDestroy () {
      window.tinymce.remove('#tincyme') //一定要销毁 否则每次都需要刷新页面才能初始化
    },
  }
</script>

<style lang="less">
.tox-tinymce{
  height:390px !important;
}
.tox-tinymce-aux{
    z-index:1000000 !important;
}
.tox-statusbar{
  display:none !important;
}
</style>